package pers.cz.testNg;

import com.alibaba.fastjson.JSON;
import pers.cz.encrypt.DesUtil;
import pers.cz.kettle.DataSyncUtil;
import pers.cz.mapper.AutoTestCaseParamsSqlMapper;
import pers.cz.mapper.DatabaseDtlMapper;
import pers.cz.model.AutoTestCaseParamsSql;
import pers.cz.model.DatabaseDtl;
import pers.cz.spring.SpringContextUtil;
import entity.DataBaseParamter;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: PostGirl-panent
 * @description: 参数为自定义sql获取
 * @author: Cheng Zhi
 * @create: 2021-11-25 17:24
 **/
public class SqlMethodJudgeImpl implements IMethodJudge {
    @Override
    public List<String[]> splitParam(Integer paramId, String params) {

        List<String[]> resultList = new ArrayList<>();

        // 查询数据库
        AutoTestCaseParamsSql autoTestCaseParamsSql = SpringContextUtil.getBean(AutoTestCaseParamsSqlMapper.class).selectByPrimaryKey(paramId);

        // 获取执行环境
        Integer dataBaseId = autoTestCaseParamsSql.getDataBaseId();
        DatabaseDtl databaseDtl = SpringContextUtil.getBean(DatabaseDtlMapper.class).selectByPrimaryKey(dataBaseId);

        // 获取执行参数
        String sqlParam = "{\n" +
                "                    \"ip\":"+databaseDtl.getIp()+",\n" +
                "                    \"port\":" + databaseDtl.getPort()+",\n" +
                "                    \"type\": " + databaseDtl.getType() +",\n" +
                "                    \"connectionName\": "+ databaseDtl.getConnectionName()+",\n" +
                "                    \"databaseName\": " + databaseDtl.getDatabaseName()+ ",\n" +
                "                    \"username\": "+ databaseDtl.getUsername()+",\n" +
                "                    \"password\": "+ DesUtil.decode(databaseDtl.getPassword())+"\n" +
                "                };";
        String str = JSON.toJSONString(sqlParam); //转化成JSON字符串
        DataBaseParamter paramter  = JSON.parseObject(str,DataBaseParamter.class); //将JSON转化成对象

        List<String> results = null;
        try {
            results = DataSyncUtil.executeSql(paramter, autoTestCaseParamsSql.getSqlCode());
            String[] stringArray = new String[results.size()];
            int i = 0;
            for (String result : results) {
                stringArray[i] = result;
                i++;
            }
            resultList.add(stringArray);
        } catch (Exception e) {
            //e.printStackTrace();
        }

        return resultList;
    }
}
